import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { MenuService } from '@/service/menu.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute } from '@angular/router';
import { Menu } from '@/models/Menu';
import { ApiResponse } from '@/models/ApiResponse';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-menuform',
  templateUrl: './menuform.component.html',
  styleUrls: ['./menuform.component.less']
})

export class MenuformComponent implements OnInit {

  actionName: string = "新增";
  form1!: FormGroup;
  // 编辑
  editInfo: { id?: number } = {};
  nodes = [];

  parentNodes: Array<any> = [];

  constructor(
    private location: Location,
    private formBuilder: FormBuilder,
    private menuSrv: MenuService,
    private message: NzMessageService,
    private activatedRoute: ActivatedRoute) { }

  ngOnInit(): void {
    this.menuSrv.getMenuTree().subscribe(el => {
      let fnRepeat = function (arr: Array<any> | null | undefined): Array<any> {
        if (!arr || arr.length == 0) {
          return [];
        }
        let nodes = arr.map((a: Menu) => {
          return {
            key: a.menu_id,
            title: a.menu_name,
            isLeaf: a.is_leaf,
            children: a.is_leaf ? [] : fnRepeat(a.children)
          }
        })

        return nodes;
      }

      let nodes = fnRepeat(el)
      this.parentNodes = nodes;
    })

    // 菜单参数
    this.activatedRoute.queryParams.subscribe((param) => {
      this.editInfo = param
      let group = {
        menu_id: [0, []],
        parent_id: [null, [Validators.required]],
        menu_name: [null, [Validators.minLength(2), Validators.required]],
        menu_path: [null, [Validators.required]],
        menu_icon: [null, []],
        order_num: [200, [Validators.required]],
      }
      this.form1 = this.formBuilder.group(group);

      if (this.editInfo.id != void 0) {
        this.actionName = "编辑";
        this.loadMenu(this.editInfo.id).subscribe(el => {
          if (el.flag) {
            let data: Menu = el.data as Menu;
            this.form1.patchValue(data)
          } else {
            this.message.create('error', el.message);
          }
        });

      }
    });
  }

  goback() {
    this.location.historyGo(-1);
  }

  loadMenu(menu_id: number): Observable<ApiResponse> {
    return this.menuSrv.getMenu(menu_id);
  }

  submitForm(): void {
    // 新增目录时只有一个字段，不使用整体的表单验证
    // let isAddDir = this.validateForm.get('kind')?.value == 'dir'
    // if (isAddDir) {
    //   this.validateForm.get('parent_id')?.setValue(-1);
    //   this.validateForm.get('menu_path')?.setValue('/');
    // }

    // 新增子菜单
    if (this.form1.valid) {
      let order = this.form1.get('order_num')!.value;
      this.form1.get('order_num')!.setValue(order * 1);
      this.menuSrv.createMenu(this.form1.value).subscribe(el => {
        if (el.flag) {
          this.message.create('success', el.message);
          this.goback();
        } else {
          this.message.create('error', el.message);
        }
      })

    } else {
      Object.values(this.form1.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

}
